package org.mayuanxiaonong.timserver.handler;

import org.mayuanxiaonong.timserver.config.Config;
import org.mayuanxiaonong.timserver.packet.Packet;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * 心跳机制处理器
 * 
 * @author 9527
 *
 */
public class HeartBeatHandler extends SimpleChannelInboundHandler<Packet> {

	int failTimes = 0;
	static Packet ping = new Packet(Packet.Type.PING);
	static Packet pong = new Packet(Packet.Type.PONG);

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
			throws Exception {
		if (evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent) evt;
			if (event.state() == IdleState.READER_IDLE) {
				if (failTimes < Config.getInstance().getHeartBeatRetry()) {
					failTimes++;
					ctx.writeAndFlush(ping);
				} else {
					// 关闭连接

				}
			}
		} else {
			super.userEventTriggered(ctx, evt);
		}
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Packet msg)
			throws Exception {
		if (msg.getType() == Packet.Type.PING) {
			failTimes = 0;
			ctx.writeAndFlush(pong);
		} else {
			ctx.fireChannelRead(msg);
		}
	}

}
